package pers.corvey.studyjava.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import pers.corvey.studyjava.model.Course;
import pers.corvey.studyjava.model.form.CourseForm;
import pers.corvey.studyjava.service.CourseService;

@Controller
@RequestMapping("/courseCategorys/{categoryId}/courses")
public class CourseController {

    @Autowired
    private CourseService courseService;
    
    @GetMapping(value="/{courseId}", headers="Accept=text/html")
    public String show() {
        return "forward://html/showCourse.html";
    }
    
    @GetMapping(value="/addCourse", headers="Accept=text/html")
    public String showAddPage() {
        return "forward://addCourse.html";
    }
    
    @GetMapping
    @ResponseBody
    public Iterable<Course> getCourses(@PathVariable String categoryId) {
        return courseService.getByCategoryId(categoryId);
    }
    
    @GetMapping(value="/{courseId}")
    @ResponseBody
    public Course getCourse(@PathVariable String courseId) {
        Course course = courseService.getCourseById(courseId);
        return course;
    }
    
    @PostMapping
    @ResponseBody
    public Course createCourse(CourseForm courseForm) {
        courseForm.validate();
        Course course = courseForm.toCourse();
        return courseService.createCourse(course);
    }
    
    @PutMapping("/{courseId}")
    @ResponseBody
    public Course updateCourse(@PathVariable String courseId, CourseForm courseForm) {
        courseForm.validate();
        Course course = courseForm.toCourse();
        course.setId(courseId);
        return courseService.updateCourse(course);
    }
    
    @DeleteMapping("/{courseId}")
    @ResponseBody
    public void deleteCourseById(@PathVariable String courseId) {
        courseService.deleteCourseById(courseId);
    }
}
